package com.study.juc2;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author study
 * @version 1.0
 * @date 2020/9/22 22:13
 */
public class ReadWriteLockDemo {
    public static void main(String[] args) {
        MyCache myCache = new MyCache();
        for (int i = 0; i < 5; i++) {
            int finalI = i;
            new Thread(() -> {
                myCache.put(String.valueOf(finalI), Thread.currentThread().getName());
            }, String.valueOf(i)).start();
        }
        for (int i = 0; i < 5; i++) {
            int finalI = i;
            new Thread(() -> {
                myCache.get(String.valueOf(finalI));
            }, String.valueOf(i)).start();
        }
    }
}

class MyCache {
    private volatile Map<String, Object> map = new HashMap();
    private ReadWriteLock lock = new ReentrantReadWriteLock();

    public void put(String key, String value) {

        lock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "\t写入中");
            map.put(key, value);
            TimeUnit.MILLISECONDS.sleep(200);
            System.out.println(Thread.currentThread().getName() + "\t写入完成");
        } catch (Exception e) {

        } finally {
            lock.writeLock().unlock();
        }


    }

    public void get(String key) {
        lock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + "\t读取中");
            try {
                TimeUnit.MILLISECONDS.sleep(200);
            } catch (InterruptedException e) {
            }
            map.get(key);
            System.out.println(Thread.currentThread().getName() + "\t读取完成");
        } finally {
            lock.readLock().unlock();
        }


    }

}
